package com.example.game

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import kotlinx.coroutines.*

class CardGameActivity : AppCompatActivity() {

    // Model
    private lateinit var gameModel: GameModel

    // View components
    private lateinit var cardViews: Array<ImageView>
    private lateinit var scoreText: TextView
    private lateinit var restartButton: Button

    // Coroutine scope for handling delays
    private val activityScope = CoroutineScope(Dispatchers.Main + SupervisorJob())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_card_game)

        // Set title
        title = getString(R.string.card_game_title)

        // Initialize model
        gameModel = GameModel()

        // Initialize views
        initializeViews()

        // Set up event listeners
        setupEventListeners()

        // Update UI
        updateUI()

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.card_grid)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    private fun initializeViews() {
        scoreText = findViewById(R.id.score_text)

        // Initialize card views array
        cardViews = arrayOf(
            findViewById(R.id.card_0), findViewById(R.id.card_1), findViewById(R.id.card_2), findViewById(R.id.card_3),
            findViewById(R.id.card_4), findViewById(R.id.card_5), findViewById(R.id.card_6), findViewById(R.id.card_7),
            findViewById(R.id.card_8), findViewById(R.id.card_9), findViewById(R.id.card_10), findViewById(R.id.card_11),
            findViewById(R.id.card_12), findViewById(R.id.card_13), findViewById(R.id.card_14), findViewById(R.id.card_15)
        )

        restartButton = findViewById(R.id.restart_button)
    }

    private fun setupEventListeners() {
        // Set up card click listeners
        cardViews.forEachIndexed { index, imageView ->
            imageView.setOnClickListener {
                onCardClicked(index)
            }
        }

        // Set up restart button listener
        restartButton.setOnClickListener {
            restartGame()
        }
    }

    private fun onCardClicked(cardIndex: Int) {
        // 如果游戏已结束，不处理点击
        if (gameModel.isGameFinished()) return

        // 如果当前已有两张卡片翻转且正在等待翻回，不处理点击
        if (gameModel.getFlippedCardIndices().size == 2) return

        // 翻转卡片
        val isMatch = gameModel.flipCard(cardIndex)

        // 更新UI
        updateCardView(cardIndex)

        if (isMatch) {
            // 匹配成功，检查游戏是否结束
            if (gameModel.isGameFinished()) {
                showGameOverMessage()
            }
        } else if (gameModel.getFlippedCardIndices().size == 2) {
            // 翻转了两张不匹配的卡片，延迟翻回
            activityScope.launch {
                delay(2000) // 2秒延迟
                val cardsToFlipBack = gameModel.checkAndFlipBack()
                cardsToFlipBack.forEach { index ->
                    updateCardView(index)
                }
            }
        }

        // 更新分数显示
        updateScoreDisplay()
    }

    private fun updateCardView(cardIndex: Int) {
        val card = gameModel.cards[cardIndex]
        val imageView = cardViews[cardIndex]

        if (card.isFlipped && card.isMatched) {
            // 已匹配的卡片，显示正面
            imageView.setImageResource(card.imageResId)
            imageView.isClickable = false // 已匹配的卡片不可点击
        } else if (card.isFlipped) {
            // 翻转但未匹配的卡片，显示正面
            imageView.setImageResource(card.imageResId)
        } else {
            // 未翻转的卡片，显示背面
            imageView.setImageResource(gameModel.cardBackResId)
        }
    }

    private fun updateUI() {
        // 更新所有卡片视图
        gameModel.cards.forEachIndexed { index, _ ->
            updateCardView(index)
        }

        // 更新分数显示
        updateScoreDisplay()
    }

    private fun updateScoreDisplay() {
        scoreText.text = "得分: ${gameModel.currentScore}"
    }

    private fun restartGame() {
        gameModel.resetGame()
        updateUI()
        Toast.makeText(this, "游戏重新开始！", Toast.LENGTH_SHORT).show()
    }

    private fun showGameOverMessage() {
        val message = getString(R.string.game_over_message, gameModel.currentScore)
        Toast.makeText(this, message, Toast.LENGTH_LONG).show()
        
        // 返回游戏分数给MainActivity
        returnGameScore()
    }

    private fun returnGameScore() {
        val resultIntent = Intent().apply {
            putExtra(MainActivity.EXTRA_GAME_SCORE, gameModel.currentScore)
        }
        setResult(Activity.RESULT_OK, resultIntent)
    }

    override fun onDestroy() {
        super.onDestroy()
        // 取消所有协程
        activityScope.cancel()
    }

    override fun onBackPressed() {
        // 用户按返回键时也返回当前分数
        returnGameScore()
        super.onBackPressed()
    }
}


